package com.example.club.clubmanage.net;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.club.clubmanage.Constant;
import com.example.club.clubmanage.model.BaseDto;
import com.example.club.clubmanage.model.BaseVo;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by chenguojun on 16/3/28.
 */
public class NetworkWrapper {
    private static final String TAG = "NetworkWrapper";
    private static final int DEFAULT_TIMEOUT = 15;
    private  MyService myService;
    private Retrofit retrofit;
    private Observable observable;
    //构造方法私有
    private NetworkWrapper() {
        //创建一个OkHttpClient并设置超时时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);


        retrofit = new Retrofit.Builder()
                .client(builder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(Constant.Gateway.server)
                .build();
        myService = retrofit.create(MyService.class);
    }
    //在访问NetworkWrapper时创建单例
    private static class SingletonHolder{
        private static final NetworkWrapper INSTANCE = new NetworkWrapper();
    }
    //获取单例
    public static NetworkWrapper getInstance(){
        return SingletonHolder.INSTANCE;
    }


    private static Map<String, Object> objectToMap(Object obj){
        if(obj == null){
            return null;
        }
        Map<String, Object> map = new HashMap<>();
//        Gson gson = new Gson();
        JSONObject jsonObject;
        String jsonString = JSON.toJSONString(obj);
        Log.d(TAG,"objectToMap:"+jsonString);
        try {
//            jsonObject = new JSONObject(gson.toJson(obj));
            jsonObject = new JSONObject(jsonString);
            Iterator keys = jsonObject.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                String value;
                try {
                    value = jsonObject.get(key).toString();
                    map.put(key,value);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return map;
    }
    // 普通用户登录
    public void login(Subscriber<BaseDto> subscriber, BaseVo vo) {
        observable = myService.login(objectToMap(vo));
        toSubscribe(observable, subscriber);
    }


    private <T> void toSubscribe(Observable<T> o, Subscriber s){
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

//    /**
//     * 用来统一处理Http的ret,并将HttpResult的Data部分剥离出来返回给subscriber
//     * 由于服务器返回的类型不统一,暂无法分装
//     * @param <T>   Subscriber真正需要的数据类型，也就是Data部分的数据类型
//     */
//    private class HttpResultFunc<T> implements Func1<BaseVo, T>{
//        @Override
//        public T call(BaseVo BaseVo) {
//            return (T)BaseVo;
//        }
//    }


    public static Map<String, Object> jsonToMap(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }

    public static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

